﻿using System;
using System.Collections.Generic;
using System.Linq;
using ControleRepresentante.Logic.Models;
using WebSite.Controllers;
using WebSite.ViewModels.Fields;

namespace WebSite.ViewModels.IndexViewModels
{
    public abstract class AttributeHolderIndexViewModel<TModel> : IndexViewModel<TModel>, IAttributeHolderIndexViewModel
        where TModel : AttributeHolder
    {
        public IEnumerable<AttributeItem> Attributes { get; set; }

        protected AttributeHolderIndexViewModel(string title)
            : base(title)
        {
        }

        protected override IEnumerable<IField> GetSearchFields()
        {
            List<IField> result = new List<IField>();

            if (Attributes != null)
            {
                foreach (AttributeItem attribute in Attributes)
                {
                    string fieldName = "_" + attribute.Name.Replace(' ', '_');
                    result.Add(new AutoCompleteField(attribute.Name, fieldName, attribute.Value, "SearchAttribute", ControllerName, new { id = attribute.Id }));
                }
            }

            result.AddRange(base.GetSearchFields());
            return result;
        }

        protected override void RegisterColumns(IndexColumnDefinitionsCollectionWrapper<TModel> indexColumnDefinitionsCollectionWrapper)
        {
            if (Attributes != null)
            {
                foreach (AttributeItem attributeItem in Attributes)
                {
                    AttributeTemplateHandler attributeTemplateHandler = new AttributeTemplateHandler(attributeItem);
                    indexColumnDefinitionsCollectionWrapper.Register(attributeItem.Attribute, attributeTemplateHandler.Template);
                }
            }
        }

        private class AttributeTemplateHandler
        {
            private readonly AttributeItem m_AttributeItem;

            public AttributeTemplateHandler(AttributeItem attributeItem)
            {
                m_AttributeItem = attributeItem;
            }

            public object Template(AttributeHolder x)
            {
                AttributeValue attributeValue = x.AttributeValues.FirstOrDefault(y => y.Attribute.Id == m_AttributeItem.Attribute.Id);
                return attributeValue == null ? String.Empty : attributeValue.Value;
            }
        }
    }

    public class AttributeItem
    {
        public Guid Id { get { return Attribute.Id; } }
        public string Name { get { return Attribute.Name; } }
        public ControleRepresentante.Logic.Models.Attribute Attribute { get; private set; }
        public string Value { get; set; }

        public AttributeItem(ControleRepresentante.Logic.Models.Attribute attribute)
        {
            Attribute = attribute;
        }
    }
}